use std::mem::MaybeUninit;

use actix_web::{dev::ServerHandle, App, HttpServer};

use crate::{
    cfg::{HTML_PATH, HTML_ROOT, WEB_SERVE_ADDR},
    error::AppErr,
};

mod api;

mod req;
mod res;
mod session;

static mut SERVER: MaybeUninit<ServerHandle> = MaybeUninit::uninit();

pub async fn stop() {
    let handle = unsafe { SERVER.assume_init_ref() };
    handle.stop(true).await;
}

pub async fn init() -> Result<(), AppErr> {
    session::init();

    let app = || {
        let file_server = actix_files::Files::new(HTML_ROOT, HTML_PATH);
        App::new().service(file_server).configure(api::register)
    };

    let serve = HttpServer::new(app).bind(WEB_SERVE_ADDR)?.run();

    unsafe {
        SERVER.write(serve.handle());
    }

    println!("web run:{}", WEB_SERVE_ADDR);

    serve.await?;

    Ok(())
}
